<?php
namespace LoginTool;
class WechatOauth{
    private $appid;
    private $appsecret;
    public  $error=[];
    public function __construct($appid = '', $appsecret = ''){
        $this->appid        = $appid;
        $this->appsecret    = $appsecret;
    }
    public function getCode($url=''){
        $url = urlencode($url);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redire";
        header('Location: ' . $url,true);
    }
    /**
     * 微信登录
     * @param  string $code [description]
     * @return [type]       [description]
     */
    public function login($code = ''){
        $accessTokenData = $this->getAccessToken($code);
        if (isset($accessTokenData['errcode'])) {
            $this->error = $accessTokenData;
            return false;
        }
        $user_info = $this->getUserinfo($accessTokenData['openid'], $accessTokenData['access_token']);
        if (isset($user_info['errcode'])) {
            $this->error = $user_info;
            return false;
        }
        return $user_info;
    }

    /**
     * 获取用户信息
     * @param  [type] $openid       [description]
     * @param  [type] $access_token [description]
     * @return [type]               [description]
     */
    protected function getUserinfo($openid,$access_token){
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}";
        $result = $this->curl($url);
        return json_decode($result, true);
    }

    /**
     * 通过 code 获取 access_token
     * @param  string $code [description]
     * @return [type]       [description]
     */
    protected function getAccessToken($code=''){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";

        $result = $this->curl($url);
         return json_decode($result, true);
    } 
    /**
     * 发起http请求
     * @param  string $url 请求地址
     * @return string unknown    请求返回的内容 
     */
    protected function curl($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}